<?php

namespace stlswm\PiaoZoneAe\Trusteeship\Business;

use Exception;
use GuzzleHttp\Exception\GuzzleException;
use stlswm\PiaoZoneAe\Trusteeship\Client;
use stlswm\PiaoZoneAe\Trusteeship\Request\InvoiceQueryByCodeReq;
use stlswm\PiaoZoneAe\Trusteeship\Response\InvoiceQueryRes;

/**
 * Class InvoiceQuery
 * @package stlswm\PiaoZone\Business
 */
class InvoiceQueryByCode
{
    /**
     * @param  Client                 $client
     * @param  InvoiceQueryByCodeReq  $invoiceQueryReq
     * @return InvoiceQueryRes
     * @throws GuzzleException
     * @throws Exception
     */
    public static function req(
        Client $client,
        InvoiceQueryByCodeReq $invoiceQueryReq
    ): InvoiceQueryRes {
        $response = $client->request("/m7/bill/invoice/code/query", $invoiceQueryReq, [
            'access_token' => $client->getToken(),
            'reqid'        => bcmul(microtime(true), 1000, 0).mt_rand(100, 999),
        ], true);
        $resData = json_decode($response);
        if (!$resData) {
            throw new Exception('无法解析返回：'.$response);
        }
        $res = new InvoiceQueryRes();
        $res->errcode = $resData->errcode;
        $res->description = $resData->description;
        $res->originJsonStr = $response;
        if (!empty($resData->data)) {
            foreach ($resData->data as $key => $value) {
                $res->{$key} = $value;
            }
        }
        return $res;
    }
}